package com.mujin.keji.collectionsystem.module.mypager.views;

import android.Manifest;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.mujin.keji.collectionsystem.CcsApplication;
import com.mujin.keji.collectionsystem.Constant;
import com.mujin.keji.collectionsystem.R;
import com.mujin.keji.collectionsystem.base.BaseActivity;
import com.mujin.keji.collectionsystem.base.BaseDto;
import com.mujin.keji.collectionsystem.module.login.dto.LoginDto;
import com.mujin.keji.collectionsystem.module.mypager.dto.UpdateUserDto;
import com.mujin.keji.collectionsystem.module.mypager.dto.UserInfoDto;
import com.mujin.keji.collectionsystem.module.mypager.viewmodel.UserViewModel;
import com.mujin.keji.collectionsystem.permissions.PermissionsObserver;
import com.mujin.keji.collectionsystem.utils.DisplayUtil;
import com.mujin.keji.collectionsystem.utils.EmptyUtils;
import com.mujin.keji.collectionsystem.utils.FileUtil;
import com.mujin.keji.collectionsystem.utils.SPUtil;
import com.mujin.keji.collectionsystem.utils.ToastUtils;
import com.mujin.keji.collectionsystem.utils.selectphoto.SelectPhotoUtils;
import com.mujin.keji.collectionsystem.widget.CircularImageView;
import com.mujin.keji.collectionsystem.widget.SelectSexPopWindow;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 个人资料界面
 *
 * @author weishixiong
 * @Time 2018-03-20
 */
public class PersonalDataActivity extends BaseActivity implements View.OnClickListener, SelectSexPopWindow.SelectSexLisenter {
    private CircularImageView ivHead;
    private TextView tvName;
    private TextView tvId;
    private TextView tvAccount;
    private TextView tvSex;
    private TextView tvPhone;
    private TextView tvDepart;
    private TextView tvPosition;
    private UserViewModel userViewModel;
    private PopupWindow phototPop;
    private RelativeLayout rlHead;
    private View parentView;
    //裁剪的code
    private static final int PHONE_CROP = 20001;
    //相机
    private final int FROM_CAPTURE = 10001;
    //相册
    private final int FROM_ALBUM = 10002;
    private final String AUTHORITY = "com.mujin.keji.collectionsystem.fileprovider";
    private int fileType;//1 拍照 2 相册
    private RelativeLayout rlSex;
    private RelativeLayout rlPhone;
    ///裁剪之后的uri
    private Uri mCutUri;
    private SmartRefreshLayout refreshLayout;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CcsApplication.addActivity(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        getLoadingDialog().showDialog();
        initPersonData();

    }

    /**
     * 初始化用户数据
     */
    private void initPersonData() {
        userViewModel.queryUserInfo().observe(this, new Observer<BaseDto<UserInfoDto>>() {
            @Override
            public void onChanged(@Nullable BaseDto<UserInfoDto> userInfoDtoBaseDto) {
                refreshLayout.finishRefresh();
                getLoadingDialog().dismiss();
                if (userInfoDtoBaseDto.getCode() == Constant.Server.SUCCESS_CODE && userInfoDtoBaseDto.getData() != null) {
                    tvName.setText(userInfoDtoBaseDto.getData().getUserName());
                    tvAccount.setText(userInfoDtoBaseDto.getData().getUserAccount());
                    tvId.setText(userInfoDtoBaseDto.getData().getId());
                    tvSex.setText(userInfoDtoBaseDto.getData().getSex());
                    tvPhone.setText(userInfoDtoBaseDto.getData().getTelephone());
                    tvDepart.setText(userInfoDtoBaseDto.getData().getDepartment());
                    tvPosition.setText(userInfoDtoBaseDto.getData().getPosition());
                    if(EmptyUtils.isNotEmpty(userInfoDtoBaseDto.getData().getImg())){
                        Glide
                                .with(PersonalDataActivity.this)
                                .load(userInfoDtoBaseDto.getData().getImg())
                                .into(ivHead);
                    }

                } else {
                    ToastUtils.showToast(userInfoDtoBaseDto.getMsg());
                }
            }
        });


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CcsApplication.removeActivity(this);
    }

    @Override
    protected void createViewModel() {
        userViewModel = ViewModelProviders.of(this).get(UserViewModel.class);
    }

    @Override
    public int intiLayout() {
        return R.layout.activity_personaldata;
    }

    @Override
    public void initView() {
        parentView = getWindow().getDecorView();
        ivHead = (CircularImageView) findViewById(R.id.iv_head);
        tvName = (TextView) findViewById(R.id.tv_name);
        tvId = (TextView) findViewById(R.id.tv_id);
        tvAccount = (TextView) findViewById(R.id.tv_account);
        tvSex = (TextView) findViewById(R.id.tv_sex);
        tvPhone = (TextView) findViewById(R.id.tv_phone);
        tvDepart = (TextView) findViewById(R.id.tv_depart);
        tvPosition = (TextView) findViewById(R.id.tv_position);
        rlHead = (RelativeLayout) findViewById(R.id.rl_head);
        rlSex = (RelativeLayout) findViewById(R.id.rl_sex);
        rlPhone = (RelativeLayout) findViewById(R.id.rl_phone);
        setCenterTitle("个人资料", "#FFFFFF");
        setleftImage(R.drawable.image_arrow_left_white, true, null);
        refreshLayout = (SmartRefreshLayout) findViewById(R.id.refreshLayout);
        refreshLayout.setEnableLoadMore(false);
        initPhotoPopView();
    }

    /**
     * 初始化对话框
     */
    private void initPhotoPopView() {
        phototPop = new PopupWindow();
        View view = getLayoutInflater().inflate(R.layout.pop_select_photo, null);
        final LinearLayout llPopup = (LinearLayout) view.findViewById(R.id.ll_popup);
        phototPop.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        phototPop.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        phototPop.setBackgroundDrawable(new BitmapDrawable());
        phototPop.setFocusable(true);
        phototPop.setOutsideTouchable(true);
        phototPop.setContentView(view);
        RelativeLayout parent = (RelativeLayout) view.findViewById(R.id.parent);
        Button bt1 = (Button) view.findViewById(R.id.item_popupwindows_camera);
        Button bt2 = (Button) view.findViewById(R.id.item_popupwindows_Photo);
        Button bt3 = (Button) view.findViewById(R.id.item_popupwindows_cancel);
        parent.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                phototPop.dismiss();
                llPopup.clearAnimation();
            }
        });
        bt1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fileType = 1;
                RxPermissions.getInstance(PersonalDataActivity.this).request(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new PermissionsObserver() {
                    @Override
                    protected void onGetPermissionsSuccess() {
                        SelectPhotoUtils.fromCapture(PersonalDataActivity.this, AUTHORITY, FROM_CAPTURE);
                    }

                    @Override
                    protected void onGetPermissionsSuccessFailuer() {
                        ToastUtils.showToast("拍照相关权限被拒绝，无法使用拍照功能");
                    }
                });
                phototPop.dismiss();
                llPopup.clearAnimation();

            }
        });
        bt2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fileType = 2;
                RxPermissions.getInstance(PersonalDataActivity.this).request(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new PermissionsObserver() {
                    @Override
                    protected void onGetPermissionsSuccess() {
                        SelectPhotoUtils.fromAlbum(PersonalDataActivity.this, AUTHORITY, 1, FROM_ALBUM);
                    }

                    @Override
                    protected void onGetPermissionsSuccessFailuer() {
                        ToastUtils.showToast("相册相关权限被拒绝，无法使用相册功能");
                    }
                });
                phototPop.dismiss();
                llPopup.clearAnimation();
            }
        });
        bt3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                phototPop.dismiss();
                llPopup.clearAnimation();
            }
        });
    }

    @Override
    public void initData() {

    }


    @Override
    public void initListener() {
        rlHead.setOnClickListener(this);
        rlSex.setOnClickListener(this);
        rlPhone.setOnClickListener(this);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                initPersonData();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_head:
                phototPop.showAtLocation(parentView, Gravity.BOTTOM, 0, 0);
                break;
            case R.id.rl_phone:
                Intent intent = new Intent(this, UpdatePhoneActivity.class);
                intent.putExtra("phone", tvPhone.getText().toString());
                startActivity(intent);
                break;
            case R.id.rl_sex:
                new SelectSexPopWindow(this, this).showAtLocation(parentView, Gravity.BOTTOM, 0, 0);
                break;
        }
    }

    private File imageFile;
    private String filePath;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                //图库
                case FROM_ALBUM:
                    List<Uri> uriList = SelectPhotoUtils.albumResult(data);
                    Uri uri = uriList.get(0);
                    // path = SelectPhotoUtils.getRealPathFromURI(this, uri);
                    startActivityForResult(CutForPhoto(uri), PHONE_CROP);
                    break;
                //相机
                case FROM_CAPTURE:
                    String path = SelectPhotoUtils.capturePathResult();
                    startActivityForResult(CutForCamera(new File(path)), PHONE_CROP);
                    break;
                case PHONE_CROP:
                    try {
                        //获取裁剪后的图片，并显示出来
//                        Bitmap bitmap = BitmapFactory.decodeStream(
//                                getContentResolver().openInputStream(mCutUri));
//                        mUserLogoIcon.setImageBitmap(bitmap);
                        filePath = mCutUri.getPath();
                        imageFile = new File(filePath);
                        if (EmptyUtils.isNotEmpty(imageFile)) {
                            List<File> fileList = new ArrayList<>();
                            fileList.add(imageFile);
                            getLoadingDialog().showDialog();
                            userViewModel.updateImage(fileList).observe(this, new Observer<BaseDto<String>>() {
                                @Override
                                public void onChanged(@Nullable BaseDto<String> stringBaseDto) {
                                    getLoadingDialog().dismiss();
                                    if (fileType == 1) {
                                        FileUtil.deleteFile(imageFile);
                                    }
                                    if (stringBaseDto.getCode() == Constant.Server.SUCCESS_CODE) {
                                        ToastUtils.showToast("上传成功");
                                        LoginDto dto = SPUtil.getData(Constant.SP.SP, Constant.SP.LOGIN_KEY, LoginDto.class, null);
                                        dto.setImg(stringBaseDto.getData());
                                        SPUtil.putData(Constant.SP.SP, Constant.SP.LOGIN_KEY, dto);
                                        Glide
                                                .with(PersonalDataActivity.this)
                                                .load(stringBaseDto.getData())
                                                // .error(R.mipmap.future_studio_launcher) // will be displayed if the image cannot be loaded
                                                .into(ivHead);
                                    } else {
                                        getLoadingDialog().dismiss();
                                        ToastUtils.showToast(stringBaseDto.getMsg());
                                    }
                                }
                            });
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
            }

        }
    }


    @Override
    public void onSelect(final String sex) {
        final LoginDto dto = SPUtil.getData(Constant.SP.SP, Constant.SP.LOGIN_KEY, LoginDto.class, null);
        getLoadingDialog().showDialog();
        userViewModel.getLiveData(sex, dto == null ? "" : dto.getTelephone()).observe(this, new Observer<BaseDto<UpdateUserDto>>() {
            @Override
            public void onChanged(@Nullable BaseDto<UpdateUserDto> updateUserDtoBaseDto) {
                ToastUtils.showToast(updateUserDtoBaseDto.getMsg());
                getLoadingDialog().dismiss();
                if (updateUserDtoBaseDto.getCode() == Constant.Server.SUCCESS_CODE) {
                    tvSex.setText(sex);
                    dto.setSex(sex);
                    SPUtil.putData(Constant.SP.SP, Constant.SP.LOGIN_KEY, dto);
                }
            }
        });
    }

    /**
     * 相册图片裁剪
     *
     * @param uri
     * @return
     */
    @NonNull
    private Intent CutForPhoto(Uri uri) {
        try {
            //直接裁剪
            Intent intent = new Intent("com.android.camera.action.CROP");
            //设置裁剪之后的图片路径文件
            File cutfile = new File(Environment.getExternalStorageDirectory().getPath(),
                    "cutcamera.png"); //随便命名一个
            if (cutfile.exists()) { //如果已经存在，则先删除,这里应该是上传到服务器，然后再删除本地的，没服务器，只能这样了
                cutfile.delete();
            }
            cutfile.createNewFile();
            //初始化 uri
            Uri imageUri = uri; //返回来的 uri
            Uri outputUri = null; //真实的 uri
            outputUri = Uri.fromFile(cutfile);
            mCutUri = outputUri;
            // crop为true是设置在开启的intent中设置显示的view可以剪裁
            intent.putExtra("crop", true);
            // aspectX,aspectY 是宽高的比例，这里设置正方形
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            //设置要裁剪的宽高
            intent.putExtra("outputX", DisplayUtil.dip2px(this, 200)); //200dp
            intent.putExtra("outputY", DisplayUtil.dip2px(this, 200));
            intent.putExtra("scale", true);
            //如果图片过大，会导致oom，这里设置为false
            intent.putExtra("return-data", false);
            if (imageUri != null) {
                intent.setDataAndType(imageUri, "image/*");
            }
            if (outputUri != null) {
                intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
            }
            intent.putExtra("noFaceDetection", true);
            //压缩图片
            intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
            return intent;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 拍照之后，启动裁剪
     *
     * @return
     */
    @NonNull
    private Intent CutForCamera(File camerafile) {
        try {

            //设置裁剪之后的图片路径文件
            File cutfile = new File(Environment.getExternalStorageDirectory().getPath(),
                    "cutcamera.png"); //随便命名一个
            if (cutfile.exists()) { //如果已经存在，则先删除,这里应该是上传到服务器，然后再删除本地的，没服务器，只能这样了
                cutfile.delete();
            }
            cutfile.createNewFile();
            //初始化 uri
            Uri imageUri = null; //返回来的 uri
            Uri outputUri = null; //真实的 uri
            Intent intent = new Intent("com.android.camera.action.CROP");
            //拍照留下的图片
            if (Build.VERSION.SDK_INT >= 24) {
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                imageUri = FileProvider.getUriForFile(this,
                        AUTHORITY,
                        camerafile);
            } else {
                imageUri = Uri.fromFile(camerafile);
            }
            outputUri = Uri.fromFile(cutfile);
            //把这个 uri 提供出去，就可以解析成 bitmap了
            mCutUri = outputUri;
            // crop为true是设置在开启的intent中设置显示的view可以剪裁
            intent.putExtra("crop", true);
            // aspectX,aspectY 是宽高的比例，这里设置正方形
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            //设置要裁剪的宽高
            intent.putExtra("outputX", DisplayUtil.dip2px(this, 200));
            intent.putExtra("outputY", DisplayUtil.dip2px(this, 200));
            intent.putExtra("scale", true);
            //如果图片过大，会导致oom，这里设置为false
            intent.putExtra("return-data", false);
            if (imageUri != null) {
                intent.setDataAndType(imageUri, "image/*");
            }
            if (outputUri != null) {
                intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
            }
            intent.putExtra("noFaceDetection", true);
            //压缩图片
            intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
            return intent;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
